package ai_role_api

import (
	"encoding/json"
	"muziai-server/global"
	"muziai-server/models"
	"muziai-server/utils/jwts"
	"muziai-server/utils/res"

	"github.com/gin-gonic/gin"
)

type AiRoleWorkCreateRequest struct {
	RoleID           uint                `json:"roleID" binding:"required"`
	Reason           string              `json:"reason" binding:"required"`           // 申请理由
	Type             int8                `json:"type" binding:"required,oneof=1 2 3"` // 1 推荐  2  更新  3 删除
	AiRoleUpdateData *models.AiRoleModel `json:"aiRoleUpdateData"`                    // 角色更新的信息  type=2必填
}

// AiRoleWorkCreateView 创建角色工单
func (AiRoleApi) AiRoleWorkCreateView(c *gin.Context) {
	var cr AiRoleWorkCreateRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		res.FailWithError(c, err)
		return
	}
	var model models.AiRoleWorkOrderModel
	switch cr.Type {
	case 1:

	case 2:
		// 判断AiRoleUpdateData是否为空
	case 3:

	}
	_claims, _ := c.Get("claims")
	claims := _claims.(*jwts.Claims)
	// 查这个角色的创建人是不是我
	var role models.AiRoleModel
	err = global.DB.Take(&role, "user_id = ? and id = ?", claims.UserID, cr.RoleID).Error
	if err != nil {
		res.FailWithMsg(c, "角色不存在")
		return
	}

	byteData, _ := json.Marshal(cr.AiRoleUpdateData)

	err = global.DB.
		Take(&model, "ai_role_id = ? and type = ? and status = ?", cr.RoleID, cr.Type, 1).Error
	if err == nil {
		res.FailWithMsg(c, "请勿重复提交工单")
		return
	}

	err = global.DB.Create(&models.AiRoleWorkOrderModel{
		Reason:           cr.Reason,
		UserID:           claims.UserID,
		AiRoleID:         cr.RoleID,
		Type:             cr.Type,
		Status:           1,
		AiRoleUpdateData: string(byteData),
	}).Error
	if err != nil {
		res.FailWithMsg(c, "创建角色工单失败")
		return
	}

	res.OkWithMsg(c, "创建角色工单成功")
	return
}
